<template>
    <div class="height100">
        <div class="shif">
            <div
                v-for="(item, index) in data"
                :key="index"
                :class="{ ouh: requiredInfoLack === item.ids, disabled: visiblereq }"
                @click="setActive(item.ids)"
                class="item"
            >
                {{ item.name }}
                <span v-if="item.name === '全部商品'">{{ tital }}</span>
            </div>
        </div>

        <el-container class="height100">
            <el-aside width="240px" class="aside-wrapper">
                <div v-show="requiredInfoLack !== 1" v-hasPermi="['shop:cat:add', 'shop:goods:sort', 'shop:cat:sort']">
                    <el-header class="head-wrap">
                        <div class="herd-btn">
                            <button
                                @click="ClickAddClass"
                                class="button-btn"
                                style="background: #fff"
                                v-hasPermi="['shop:cat:add']"
                            >
                                <span class="iconfont icon-tianjia" style="font-size: 12px"></span>
                                <span style="font-size: 12px">添加分类</span>
                            </button>
                            <button
                                @click="switchPane"
                                class="button-btn"
                                style="background: #fff"
                                v-hasPermi="['shop:goods:sort', 'shop:cat:sort']"
                            >
                                <span class="iconfont icon-paixu" style="font-size: 12px"></span>
                                <span style="font-size: 12px">管理排序</span>
                            </button>
                        </div>
                    </el-header>
                </div>
                <div
                    class="aside-list"
                    v-if="goodCategory.data"
                    style="margin-top: 1px"
                    v-loading="loadings"
                    element-loading-text="正在加载中..."
                >
                    <el-tree
                        ref="goodCategoryTreeRef"
                        :data="goodCategory.data"
                        accordion
                        @node-click="handleNodeClick"
                        class="tree-style"
                        node-key="id"
                        :current-node-key="goodCategory.checkedKeys"
                        check-on-click-node
                        render-after-expand
                        :highlight-current="true"
                        :loading="loadings"
                    >
                        <template #default="{ data }">
                            <div class="item-wrapper" :id="data.id">
                                <div class="aside-list-item">
                                    <el-tooltip
                                        :content="data.categoryName"
                                        placement=""
                                        :disabled="data.categoryName?.length < 9"
                                    >
                                        <div class="item-name">
                                            {{ data.categoryName }}
                                        </div>
                                    </el-tooltip>
                                    <div class="item-desc">
                                        <div class="item-desc-num">商品 {{ data.goodsNum }}</div>
                                        <div class="item-desc-sort" v-if="data.children && data.children.length">
                                            分类 {{ data.children.length }}
                                        </div>
                                    </div>
                                </div>
                                <div style="position: relative; right: 0px">
                                    <div
                                        style="top: -26px; position: absolute; right: 0px"
                                        v-show="data.categoryName !== '全部' && data.topFlag === 1"
                                    >
                                        <!-- <img src="../../../assets/img/top1.png" style="width: 20px" /> -->
                                        <el-tooltip placement="right" v-if="data.weeksTime != null">
                                            <template #content>
                                                每周{{ getWeeksText(data.weeksTime) }}<br />{{ getPeriod(data.period) }}
                                            </template>
                                            <!-- <template #content v-else> 没有设置时间 </template> -->
                                            <img src="../../../assets/img/setPuls2.png" style="width: 32px" />
                                        </el-tooltip>
                                        <div v-else>
                                            <img src="../../../assets/img/setPuls2.png" style="width: 32px" />
                                        </div>
                                        <!-- <div class="card-item-icon">
                                            <span class="iconfont icon-zhiding"></span>
                                        </div> -->
                                    </div>
                                    <el-dropdown
                                        trigger="hover"
                                        @command="handleCommand"
                                        style="margin-right: 10px"
                                        v-show="data.categoryName !== '全部'"
                                        v-hasPermi="['shop:cat:add', 'shop:cat:edit', 'shop:cat:top', 'shop:cat:del']"
                                    >
                                        <el-icon><Tools /></el-icon>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <div v-hasPermi="['shop:cat:edit']">
                                                    <el-dropdown-item
                                                        command="Editname"
                                                        @click="EditNames(data)"
                                                        style="cursor: pointer"
                                                        :disabled="data.categoryName === '未分类'"
                                                    >
                                                        修改名称</el-dropdown-item
                                                    >
                                                </div>

                                                <div v-hasPermi="['shop:cat:top']">
                                                    <el-dropdown-item
                                                        command="delete"
                                                        style="cursor: pointer"
                                                        v-if="data.pid === 0"
                                                        @click="Tops(data)"
                                                        :disabled="data.categoryName === '未分类'"
                                                        >设置限时置顶</el-dropdown-item
                                                    >
                                                </div>
                                                <div v-hasPermi="['shop:cat:edit']">
                                                    <el-dropdown-item
                                                        command="delete"
                                                        style="cursor: pointer"
                                                        v-if="data.pid === 0"
                                                        @click="SettingSecond(data)"
                                                        :disabled="data.categoryName === '未分类'"
                                                        >设为二级分类</el-dropdown-item
                                                    >
                                                </div>
                                                <div v-hasPermi="['shop:cat:add']">
                                                    <el-dropdown-item
                                                        command="delete"
                                                        style="cursor: pointer"
                                                        v-if="data.pid === 0"
                                                        @click="AddSettingSecond(data)"
                                                        :disabled="data.categoryName === '未分类'"
                                                        >新增二级分类</el-dropdown-item
                                                    >
                                                </div>
                                                <div v-hasPermi="['shop:cat:edit']">
                                                    <el-dropdown-item
                                                        command="delete"
                                                        style="cursor: pointer"
                                                        v-if="data.pid !== 0"
                                                        @click="SettingFirst(data)"
                                                        :disabled="data.categoryName === '未分类'"
                                                        >设为一级分类</el-dropdown-item
                                                    >
                                                </div>
                                                <div v-hasPermi="['shop:cat:del']">
                                                    <el-dropdown-item
                                                        command="delete"
                                                        style="cursor: pointer"
                                                        @click="EditDelete(data)"
                                                        >删除</el-dropdown-item
                                                    >
                                                </div>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                </div>
                            </div>
                        </template>
                    </el-tree>
                </div>
            </el-aside>
            <el-main class="p0">
                <div class="control-wrapper">
                    <div class="mt-4">
                        <el-input
                            v-model.trim="goodsSearch"
                            placeholder="商品名称/店内码/货号"
                            class="control-input"
                            @blur="getGoodsList"
                            clearable
                            style="width: 260px"
                        >
                            <template #append>
                                <el-button
                                    :icon="Search"
                                    @click="getGoodsList"
                                    style="
                                        width: 46px;
                                        background-color: black;
                                        color: white;
                                        border-top-left-radius: 0px;
                                        border-bottom-left-radius: 0px;
                                    "
                                />
                            </template>
                        </el-input>
                    </div>

                    <!-- <div class="control-item">
                        <el-input
                            v-model="goodsSearch"
                            placeholder="商品名称"
                            class="control-input"
                            @blur="getGoodsList"
                        >
                            <template #prefix>
                                <el-icon class="el-input__icon">
                                    <search />
                                </el-icon>
                            </template>
                        </el-input>
                        <el-button @click="getGoodsList"> 搜索 </el-button>
                    </div> -->

                    <div class="btn-warp" v-if="requiredInfoLack !== 1">
                        <!--  -->
                        <!-- <div class="control-item">
                            <el-button @click="downloadGood" v-hasPermi="['goods:goods:download']">
                                下载商品
                            </el-button>
                        </div> -->

                        <!--  -->
                        <div style="margin-top: 45px; margin-left: 20px">
                            <el-button-group class="ml-4">
                                <el-button @click="setSelStatusa(1)" plain v-hasPermi="['goods:setOff']"
                                    >下架</el-button
                                >
                                <el-button
                                    @click="setSelStatusa(0)"
                                    plain
                                    style="margin-right: 0px"
                                    v-hasPermi="['goods:setOff']"
                                    >上架</el-button
                                >
                                <!-- <el-button
                                    plain
                                    @click="showDialog(editCategoryDialog)"
                                    v-hasPermi="['goods:class:modifyClass']"
                                    style="margin-right: 0px"
                                    >修改分类</el-button
                                > -->
                                <el-dropdown v-hasPermi="['goods:setSpecialty']">
                                    <el-button> 更多<i class="el-icon-arrow-down el-icon--right"></i> </el-button>
                                    <template #dropdown>
                                        <div v-show="requiredInfoLack !== '1'">
                                            <el-dropdown-menu>
                                                <el-dropdown-item @click="showDialog({ state: 1, isShow: true })"
                                                    >设置力荐</el-dropdown-item
                                                >

                                                <el-dropdown-item @click="showDialog({ state: 2, isShow: true })">
                                                    取消力荐</el-dropdown-item
                                                >
                                            </el-dropdown-menu>
                                        </div>
                                        <div v-show="requiredInfoLack === '1'">
                                            <el-dropdown-menu>
                                                <el-dropdown-item>暂无更多</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </div>
                                        <!-- <el-dropdown-item
                                                @click="showDialog(delDialog)"
                                                v-hasPermi="['goods:goods:del']"
                                            >
                                                批量删除</el-dropdown-item
                                            > -->
                                    </template>
                                </el-dropdown>
                            </el-button-group>
                        </div>
                    </div>
                </div>

                <div class="table-wrap">
                    <el-table
                        v-loading="loading"
                        ref="multipleTableRef"
                        :data="tableData.data"
                        @selection-change="handleSelectionChange"
                        class="table-style"
                        :cell-style="{ border: 'none', padding: '0px', height: '5.25rem' }"
                    >
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="pic_full" label="商品图片" width="100">
                            <template #default="scope">
                                <el-image :src="scope.row.coverPicture" />
                                <div class="goods-mask">
                                    <!-- {{ scope.row }} -->
                                    <div class="goods-tag" v-if="scope.row.isSoldOut === 1">下架</div>
                                    <div class="goods-tag" v-if="scope.row.requiredInfoLack === 1">信息缺失</div>
                                    <div class="goods-tag" v-if="scope.row.isAbnormal !== 0">商品异常</div>
                                </div>
                                <!-- <el-tag type="warning" class="lijian-tag" v-if="scope.row.isSpecialty == 1"
                                    >力荐</el-tag
                                > -->
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" label="商品名称" width="350">
                            <template #default="scope">
                                <div class="trade-name">
                                    <div class="edit-name" @click="openTradeName(scope.row)">
                                        <div style="max-width: 90%">{{ scope.row.name }}</div>
                                        <div
                                            class="trade-editname"
                                            style="width: 10%; margin-top: 4px; margin-left: 5px"
                                        >
                                            <el-icon><Edit /></el-icon>
                                        </div>
                                    </div>

                                    <div class="label-style">
                                        <div type="warning" class="litiu" v-if="scope.row.isSpecialty == 1">
                                            <span
                                                class="iconfont icon-dianzan_kuai"
                                                style="font-size: 11px; margin-left: 2px"
                                            ></span>
                                            <div style="margin-left: 3px">力推</div>
                                        </div>
                                        <div class="tag-flex-wrap">
                                            <div class="tag_wrap color1" v-if="scope.row.saleType==2">{{ saleTypeMap[scope.row.saleType] }}</div>
                                            <div class="tag_wrap color2" v-if="scope.row.availableType!=1">
                                                {{ availableTypeMap[scope.row.availableType] }}
                                            </div>

                                            <div class="tag_wrap color3" v-if="scope.row.isSingleNoDelivery == '1'">
                                                {{ isSingleNoDeliveryMap[scope.row.isSingleNoDelivery] }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="showSkuId" label="店内码/货号">
                            <template #default="scope">
                                <div class="trade-names">
                                    <div>{{ scope.row.showSkuId }}</div>
                                    <div class="trade-editnames">
                                        <!-- <el-icon>
                                            <Edit />

                                        </el-icon> -->
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="isSpecialty" label="是否力荐">
                            <template #default="scope">
                                {{ scope.row.isSpecialty ? '是' : '否' }}
                            </template>
                        </el-table-column> -->
                        <el-table-column prop="isRelation" label="关联状态">
                            <!-- <template #default="scope">
                                {{ scope.row.isRelation ? '是' : '否' }}
                            </template> -->

                            <template #default="scope">
                                <div class="trade-names">
                                    <div>{{ scope.row.isRelation ? '是' : '否' }}</div>
                                    <div class="trade-editnames">
                                        <!-- <el-icon>
                                            <Edit />
                                        </el-icon> -->
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="showPrice" label="总部价格">
                            <template #default="scope">
                                <div class="trade-name" @click="openPrice(scope.row)">
                                    <div>{{ scope.row.showPrice }}</div>
                                    <div class="trade-editname">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="showSkuIds" label="库存">
                            <template #default="scope">
                                <div class="trade-name" @click="openKucun(scope.row)">
                                    <div>{{ scope.row.stock }}</div>
                                    <div class="trade-editname">
                                        <el-icon>
                                            <Edit />
                                        </el-icon>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column
                            label="操作"
                            width="200"
                            v-hasPermi="['goods:update', 'goods:del', 'goods:setOff', 'goods:setSpecialty']"
                        >
                            <template #default="scope">
                                <div class="table-control">
                                    <div @click="editProduct(scope.row.id)" v-hasPermi="['goods:update']">编辑</div>

                                    <div
                                        v-if="requiredInfoLack !== 1 && scope.row.isSoldOut === 1"
                                        @click="setSelStatus(0, scope.row.id)"
                                        v-hasPermi="['goods:setOff']"
                                    >
                                        上架
                                    </div>
                                    <div
                                        v-if="requiredInfoLack !== 1 && scope.row.isSoldOut === 0"
                                        @click="setSelStatus(1, scope.row.id)"
                                        v-hasPermi="['goods:setOff']"
                                    >
                                        下架
                                    </div>
                                    <div @click="Dels(scope.row.id)" v-hasPermi="['goods:del']">删除</div>
                                    <!-- <div
                                        style="width: 60px"
                                        v-if="scope.row.isSpecialty == 1"
                                        @click="showDialog({ state: 2, isShow: true })"
                                        v-hasPermi="['goods:goods:clearRecommendation']"
                                    > -->
                                    <div
                                        v-if="scope.row.isSpecialty === 1 && requiredInfoLack !== 1"
                                        @click="closerem(0, scope.row.id)"
                                        v-hasPermi="['goods:setSpecialty']"
                                    >
                                        取消力荐
                                    </div>
                                    <!-- </div> -->
                                    <!-- <div>库存</div> -->
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div style="display: flex; justify-content: space-between">
                        <div style="margin-top: 15px">
                            <el-button @click="showDialog(delDialog)" v-hasPermi="['goods:del']">批量删除</el-button>
                        </div>
                        <div class="paging">
                            <el-pagination
                                @current-change="handleCurrentChange"
                                @size-change="handleSizeChange"
                                background="true"
                                layout="total, prev, pager, next, sizes"
                                :page-sizes="[10, 20, 30, 50, 100, 200]"
                                v-model:current-page="tableData.currentPage"
                                v-model:page-size="tableData.pageSize"
                                :total="tableData.totalNum"
                            >
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </el-main>
        </el-container>
        <router-view></router-view>
    </div>
    <!-- 删除商品 -->
    <ConfirmDialog
        @submit="goodsDelete"
        @close="delDialog.isShow = false"
        v-model:visible="delDialog.isShow"
        title="提示"
        message="确认删除商品吗"
        cancellation="关闭"
        determine="确认"
    ></ConfirmDialog>
    <!-- 力荐设置 -->
    <ConfirmDialog
        @submit="goodsRecommend"
        @close="recommendDialog.isShow = false"
        v-model:visible="recommendDialog.isShow"
        title="提示"
        :message="recommendDialog.state === 1 ? '是否设置所选商品为力荐？' : '是否取消选中商品力荐?'"
        cancellation="关闭"
        determine="确认"
    >
    </ConfirmDialog>
    <!-- 修改分类 -->
    <EditClass
        v-model:visible="editCategoryDialog.isShow"
        v-model:EditButtonLoading="EditButtonLoading"
        @submit="handleEditClass"
        @close="handelCoseEditClass"
        :data="checkedGoodsIdList"
    ></EditClass>
    <!-- 修改库存弹窗 -->
    <editInventory
        v-model:visible="editInventoryDialog.isShow"
        @submit="handleAddClass"
        @close="editInventoryDialog.isShow = false"
    ></editInventory>
    <!-- 删除弹窗 -->
    <ConfirmDialog
        @submit="handleDeleteConfirmed"
        @close="handleDeleteCanceled"
        v-model:visible="delDialogs.isShow"
        title="提示"
        message="确认删除商品吗"
        cancellation="关闭"
        determine="确认"
    ></ConfirmDialog>

    <EditNamePrice ref="refEditNamePrice" @submit="referesh"></EditNamePrice>
    <!-- 修改、删除 .分类 -->
    <SingleStoreEditname ref="refEditName" @submit="refresh"></SingleStoreEditname>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { goodsApi } from '@/api/goodManger'
import ConfirmDialog from '@/components/ConfirmDialog.vue' // 公共提示弹框
import EditClass from '../components/editClass.vue' //修改分类弹窗
import editInventory from '../components/editInventory.vue' //修改库存弹窗
import { Search } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router' //引入useRouter

// import { exportFile } from '@/utils/downloadFile' //导出表格
import EditNamePrice from '../components/daneditNamePrice.vue' //编辑商品名称与价格弹窗

import { useStore } from 'vuex'
import SingleStoreEditname from '../popups/SingleStoreEditname.vue'
const goodCategoryTreeRef = ref() //商品分类树
const route = useRoute()
const data = reactive([
    { name: '全部商品', ids: 0 },
    // { name: '售卖中', ids: 1 },
    // { name: '已售罄', ids: 2 },
    // { name: '已下架', ids: 3 },
    { name: '必填信息缺失', ids: 1 },
])
const refEditName = ref(null)

//全局变量
const visiblereq = ref(false)

const requiredInfoLack = ref(0)
const lineLeft = ref('0px')
// const totslelse = ref(0)
const tital = ref(0)
const setActive = index => {
    const left = index === 0 ? 0 : document.querySelectorAll('.item')[0].clientWidth
    lineLeft.value = `${left}px`
    requiredInfoLack.value = index
    // console.log(requiredInfoLack.value, '123')
    getGoodsList()
    // initData()
}

const loading = ref(false)

// const isSingleNoDeliverya = ref(0)

// import EditNamePrice from './editNamePrice.vue' //编辑商品名称与价格弹窗

const refEditNamePrice = ref(null)
const store = useStore()
const router = useRouter()
const tableData = reactive({
    data: [],
    currentPage: 1,
    pageSize: 10,
    totalNum: 0,
    isShow: false,
    scroll: 0, //table的滚动条高度
})
const goodsSearch = ref('')
const goodCategory = reactive({
    data: [],
    checkedKeys: -99,
})
const storeId = ref(0)
const emits = defineEmits(['switch', 'addClass'])
const switchPane = () => {
    emits('switch', true)
}
const ClickAddClass = () => {
    emits('addClass', true)
}
const loadings = ref(false)
const tableScrollHeight = ref() //table的滚动条高度
// 映射
// 可售时间类型
const availableTypeMap = ref({
    1: '全时段可售',
    2: '周期性可售',
    3: '指定时间可售',
})

// 	是否为“单点不送”商品
const isSingleNoDeliveryMap = ref({
    0: '',
    1: '单点不送',
})
// 可售时间类型
const saleTypeMap = ref({
    1: '正常',
    2: '预售',
})
onMounted(() => {
    goodCategory.checkedKeys = route.query.classification || -99

    storeId.value = store.state.currentStoreId

    //监听商品table的高度;保证页容量与当前页相对
    const scrollBarRef = multipleTableRef.value.$refs.scrollBarRef
    const wrapRef = scrollBarRef.wrapRef
    wrapRef.addEventListener('scroll', event => {
        tableScrollHeight.value = event.target.scrollTop
    })
    if (route.query.currentPage && route.query.pageSize) {
        tableData.currentPage = Number(route.query.currentPage)
        tableData.pageSize = Number(route.query.pageSize)
        tableData.scroll = Number(route.query.tableScrollHeight)
        restHeight.value = false
        deleteQueryParam(['currentPage', 'pageSize', 'tableScrollHeight','classification'])
    }
})
// 删除指定的查询参数(因为query参数太多，所以保存后就删除他们)
function deleteQueryParam(keys) {
    const newQuery = { ...route.query }
    // 遍历每个要删除的键
    keys.forEach(key => {
        delete newQuery[key]
    })

    // 跳转到新的URL，查询参数已删除
    router.push({ path: route.path, query: newQuery })
}
const referesh = () => {
    // store.dispatch('goods/getGoodsCategoryLists', { mtsgPoiId: 10318 }).then(res => {
    //     getGoodsList()
    // })
    if (storeId.value !== undefined) {
        store.dispatch('goods/getGoodsCategoryLists', { mtsgPoiId: storeId.value }).then(() => {
            getGoodsList()
        })
    } else {
        return
    }
}

// 点击树
const handleNodeClick = data => {
    // console.log(data, '看数据')
    if (data.id == goodCategory.checkedKeys) return
    goodCategory.checkedKeys = data.id
    tital.value = data.goodsNum
    restHeight.value = true //重置滚动条高度;
    tableData.currentPage = 1
    tableData.pageSize = 10
    getGoodsList()
}

// 获取商品列表
const getGoodsList = () => {
    let obj = {
        // isSingleNoDelivery: parseInt(isSingleNoDeliverya.value),
        isSpecialty: null,
        keyword: goodsSearch.value,
        goodsCategoryId: goodCategory.checkedKeys == '-99' ? null : goodCategory.checkedKeys,
        pageNum: tableData.currentPage,
        pageSize: tableData.pageSize,
        // requiredInfoLack: parseInt(requiredInfoLack.value),
        // mtsgPoiId: 10318,
        mtsgPoiId: storeId.value,
    }

    if (parseInt(requiredInfoLack.value) === 1) {
        obj.requiredInfoLack = parseInt(requiredInfoLack.value)
        obj.isAbnormal = 1
    }
    loading.value = true
    visiblereq.value = true
    store.dispatch('goods/getGoodLists', obj).then(() => {
        loading.value = false
        visiblereq.value = false
        if (!restHeight.value) {
            // 设置table滚动条的位置
            multipleTableRef.value.setScrollTop(tableData.scroll)
        } else {
            multipleTableRef.value.setScrollTop(0)
        }
    })
}

watch(
    () => store.state.goods.goodCategoryList,
    val => {
        if (val && val.list) {
            // 检查是否为空
            goodCategory.data = JSON.parse(JSON.stringify(val.list))
            let obj = {
                id: -99,
                categoryName: '全部',
                goodsNum: val.goodsNum,
            }
            // console.log(val, store.state.goods.goodCategoryList, ' 商品数量')
            goodCategory.data.unshift(obj)
            tital.value = val.goodsNum
            // goodCategory.checkedKeys = goodCategory.data && goodCategory.data[0].id

            if (goodCategory.checkedKeys === null) {
                goodCategory.checkedKeys = goodCategory.data && goodCategory.data[0].id
            }
            console.log(goodCategory.checkedKeys, 'goodCategory.checkedKeys分类huoqu 获取')
            nextTick(() => {
                goodCategoryTreeRef.value.setCurrentKey(goodCategory.checkedKeys, true)
                if (goodCategory.checkedKeys != -99) {
                    console.log('不是全部分类')
                    scrollCurrentNode()
                }
            })
            console.log(goodCategory.checkedKeys, 'goodCategory.checkedKeys分类')

            loadings.value = false

            getGoodsList()
        } else {
            goodCategory.data = []
        }
    },
)
// 选择并滚动当可见区域
const scrollCurrentNode = () => {
    goodCategoryTreeRef.value.setCurrentKey(goodCategory.checkedKeys, true)
    let parentNode = goodCategoryTreeRef.value.$el
    nextTick(() => {
        const node = document.querySelector('.el-tree-node.is-current')
        console.log(node, '看node节点')
        let treeNode = goodCategoryTreeRef.value.getNode(goodCategory.checkedKeys)
        console.log(treeNode, 'treeNode看节点')
        if (node) {
            setTimeout(() => {
                // 获取滚动的高度
                let scrollHeight = node.offsetTop - parentNode.scrollTop - parentNode.offsetHeight / 2 + 80
                parentNode.scrollBy({ top: scrollHeight, behavior: 'smooth' })
                if (treeNode.childNodes.length > 0) {
                    treeNode.expanded = true
                }
            }, 200)
        }
    })
}
watch(
    () => store.state.goods.goodsList,
    val => {
        // console.log(store.state.goods.goodsList, 'sdadadas')
        tableData.data = val.list
        // console.log(tableData.data, 'ssss')

        tableData.totalNum = val.total
    },
)

const restHeight = ref(true) //table滚动的高度是否重置
// 分页按钮 上一页/下一页(前端分页)
const handleCurrentChange = val => {
    tableData.currentPage = val
    restHeight.value = true
    getGoodsList()
}
// 根据每页显示的条数查询 按钮
const handleSizeChange = size => {
    tableData.pageSize = size
    restHeight.value = true
    getGoodsList()
}

const multipleTableRef = ref()

const delDialog = reactive({
    isShow: false,
})

// 选中的商品id
const checkedGoodsIdList = ref([])
// 表格选择
const handleSelectionChange = val => {
    let goodsIdList = []
    for (let index = 0; index < val.length; index++) {
        const element = val[index]
        goodsIdList.push(element.id)
    }
    checkedGoodsIdList.value = goodsIdList
    // console.log('oooooo', checkedGoodsIdList.value)
}
//上下架
const setSelStatusa = type => {
    let obj = {
        isSoldOut: type,
        spuIdList: checkedGoodsIdList.value,
        // mtsgPoiId: 10318,
        mtsgPoiId: storeId.value,
    }
    // console.log(obj, 'sssss')
    // console.log(checkedGoodsIdList.value.length, 'sssss')
    if (checkedGoodsIdList.value.length > 0) {
        goodsApi.singlegoodstatuslist(obj).then(res => {
            // console.log('res', res)
            if (res.data.code == 0) {
                ElMessage.success('设置成功')
                getGoodsList()
            } else {
                ElMessage.error(res.data.message)
            }
        })
    } else {
        ElMessage.error('请选择商品')
    }
}

const CancelPush = ref([])

const showDialog = type => {
    // console.log('delDialog.list', type.isShow)
    // if (type.state === 2) {
    //     recommendDialog.isShow = type.isShow
    //     recommendDialog.state = type.state
    //     // CancelPush.value = tableData.data.map(v => {
    //     //     return v.id
    //     // })
    //     // console.log('111111111111111111111111', CancelPush.state);
    //     return
    // }
    if (checkedGoodsIdList.value?.length < 1) {
        ElMessage.error('请选择商品')
    } else if (type.state) {
        recommendDialog.isShow = type.isShow
        recommendDialog.state = type.state
    } else {
        type.isShow = true
    }
}

// // 取消力推
// const CancelPush = (type) => {
//     recommendDialog.isShow = type.isShow
//     recommendDialog.state = type.state
// }

// 修改库存

const editInventoryDialog = reactive({
    isShow: false,
})

// 导出商品
// const downloadGood = () => {
//     let obj = {
//         // mtsgPoiId: 10318,
//         mtsgPoiId: storeId.value,
//     }
//     goodsApi.singleexport(obj).then(res => {
//         exportFile(res)
//         // console.log(res, 'singleexport')
//     })
// }

const delDialogs = ref({ isShow: false })
const deleteId = ref(null) // 存储要删除的商品ID
// 删除商品
function Dels(id) {
    delDialogs.value.isShow = true
    deleteId.value = id
}
//删除
function handleDeleteConfirmed() {
    const spuIdList = deleteId.value ? [deleteId.value] : checkedGoodsIdList.value

    goodsApi.singledelgood({ spuIdList, mtsgPoiId: storeId.value }).then(res => {
        // goodsApi.singledelgood({ spuIdList, mtsgPoiId: 10318 }).then(res => {
        // console.log('res', res)
        if (res.data.code == 0) {
            ElMessage.success('删除成功')
            getGoodsList()
            referesh()
        } else {
            // ElMessage.error('删除失败')
            ElMessage.error(res.data.message)
        }
        delDialogs.value.isShow = false
    })
}
//删除弹窗
function handleDeleteCanceled() {
    delDialogs.value.isShow = false
}

// 修改分类
const editCategoryDialog = reactive({
    isShow: false,
})

const EditButtonLoading = ref(false) //弹框确认按钮的loading效果

const handleEditClass = Backhaul => {
    // console.log('Backhaul', Backhaul)
    let obj = {
        gooodsIds: [...checkedGoodsIdList.value],
        targetCategoryIds: [...Backhaul.targetCategoryIds],
        updateType: Backhaul.updateType,
    }
    EditButtonLoading.value = true
    goodsApi
        .editCategory(obj)
        .then(res => {
            EditButtonLoading.value = false
            if (res.data.code == 0) {
                ElMessage.success('设置成功')
                referesh()
                editCategoryDialog.isShow = false
            } else {
                ElMessage.error(res.data.message)
            }
        })
        .catch(() => {
            EditButtonLoading.value = false
        })
}
// 关闭修改分类弹框
const handelCoseEditClass = () => {
    editCategoryDialog.isShow = false
    EditButtonLoading.value = false
}

// 删除商品批量
const goodsDelete = () => {
    // goodsApi.singledelgood({ spuIdList: checkedGoodsIdList.value, mtsgPoiId: 10318 }).then(res => {
    goodsApi.singledelgood({ spuIdList: checkedGoodsIdList.value, mtsgPoiId: storeId.value }).then(res => {
        // console.log('res', res)
        if (res.data.code == 0) {
            ElMessage.success('删除成功')
            referesh()
        } else {
            // ElMessage.error('删除失败')
            ElMessage.error(res.data.message)
        }
        delDialog.isShow = false
    })
}

// 设置力荐
const recommendDialog = reactive({
    isShow: false,
})

// 设置力荐
const goodsRecommend = () => {
    let subscript = CancelPush.value.length > 0 ? true : false

    let obj = {
        isSpecialty: recommendDialog.state,
        spuIdList: subscript ? CancelPush.value : checkedGoodsIdList.value,
        // mtsgPoiId: 10318,
        mtsgPoiId: storeId.value,
    }
    // console.log(obj)
    // console.log(CancelPush.value.length)
    goodsApi.singlelistrecommend(obj).then(res => {
        // console.log('res', res)
        if (res.data.code == 0) {
            ElMessage.success('设置成功')
            CancelPush.value = []
            getGoodsList()
        } else {
            // ElMessage.error('设置失败')
            ElMessage.error(res.data.message)
        }
        recommendDialog.isShow = false
    })
}

const closerem = (type, ids) => {
    // console.log(type, ids)
    let obj = {
        isSpecialty: type,
        spuIdList: [ids],
        // mtsgPoiId: 10318,
        mtsgPoiId: storeId.value,
    }
    goodsApi.singlelistrecommend(obj).then(res => {
        // console.log('res', res)
        if (res.data.code == 0) {
            ElMessage.success('设置成功')
            CancelPush.value = []
            getGoodsList()
        } else {
            // ElMessage.error('设置失败')
            ElMessage.error(res.data.message)
        }
        recommendDialog.isShow = false
    })
}

// 设置商品上下架
const setSelStatus = (type, id) => {
    let obj = {
        isSoldOut: type,
        spuIdList: [id],
        // mtsgPoiId: 10318,
        mtsgPoiId: storeId.value,
    }
    goodsApi.singlegoodstatuslist(obj).then(res => {
        // console.log('res', res)
        if (res.data.code == 0) {
            ElMessage.success('设置成功')
            getGoodsList()
        } else {
            // ElMessage.error('设置失败')
            ElMessage.error(res.data.message)
        }
    })
}

// 编辑商品
function editProduct(id) {
    // let params = { type: 'modify', id: id }
    // router.push({ name: 'singleNew', state: { params } })
    router.push({
        path: '/singleNew',
        query: {
            type: 'modify',
            id: id,
            classification: goodCategory.checkedKeys,
            currentPage: tableData.currentPage,
            pageSize: tableData.pageSize,
            tableScrollHeight: tableScrollHeight.value,
        },
    })
}
// 打开编辑商品名称模态框
function openTradeName(row) {
    store.dispatch('checkPermissionsFn', 'goods:update').then(res => {
        if (res) {
            refEditNamePrice.value.openEditName(row)
        }
    })
}
//打开编辑价格模态框
function openPrice(row) {
    store.dispatch('checkPermissionsFn', 'goods:update').then(res => {
        if (res) {
            refEditNamePrice.value.openEditPrice(row)
        }
    })
}
// 打开编辑商品库存模态框
function openKucun(row) {
    store.dispatch('checkPermissionsFn', 'goods:update').then(res => {
        if (res) {
            refEditNamePrice.value.openEditKucun(row)
        }
    })
}

//分类删除
const EditDelete = row => {
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditDelete(row)
}

//分类名称
const EditNames = row => {
    // console.log(row)
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditfname(row)
}
//分类置顶
const Tops = row => {
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditTop(row)
}
//设置为二级分类
const SettingSecond = row => {
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditSettingSecond(row)
}
//设置为一级分类
const SettingFirst = row => {
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditSettingFirst(row)
}
//新增二级分类
const AddSettingSecond = row => {
    goodCategory.checkedKeys = row.id
    refEditName.value.openEditAddSettingSecond(row)
}
function refresh() {
    referesh()
}
//转换日期
const getWeeksText = weeksTime => {
    if (weeksTime == null) {
        return
    }
    const weeks = weeksTime.split(',').map(Number)
    const weekdays = ['一', '二', '三', '四', '五', '六', '日']
    if (weeks.length === 1) {
        return weekdays[weeks[0] - 1]
    } else {
        return weeks.map(week => weekdays[week - 1]).join('、')
    }
}
const getPeriod = period => {
    if (period == null) {
        return
    }

    // 将逗号替换为顿号
    const replacedPeriod = period.replace(/,/g, '、')

    return replacedPeriod
}
</script>

<style lang="less" scoped>
.height100 {
    height: 100%;

    .disabled {
        pointer-events: none;
        cursor: not-allowed;
    }
    .ouh {
        color: #3f78f6;
        border-bottom: 2px solid #3f78f6;
    }

    .shif {
        width: 100%;
        margin-left: 1.15rem;
        font-size: 0.875rem;
        display: flex;
        position: absolute;
        // position: fixed;
        // top: 195px;
        top: 0px;
        border-bottom: #ededed solid 1px;
    }

    .item {
        padding: 10px;
        position: relative;
        cursor: pointer;
        margin-right: 15px;
        // border-bottom: 1px solid #f6f6f6;
    }
}

.aside-wrapper {
    display: flex;
    flex-direction: column;
    border-right: 1px solid #ededed;
    width: 13.1875rem;
    height: 100%;
}

.aside-list {
    flex-grow: 1;
    display: flex;
    flex-direction: column;
    position: relative;
    :deep(.el-aside) {
        display: flex;
        flex-direction: column;
    }

    .tree-style {
        flex-grow: 1;
        overflow-y: scroll;
        height: 0;
    }
}

.table-wrap {
    padding: 0.9375rem;
    padding-bottom: 2px;
    padding-left: 0px;
    display: flex;
    flex: auto !important;
    flex-direction: column;
}

.table-style {
    flex-grow: 1;
    /* overflow-y: scroll; */
    height: 0;
}

.head-wrap {
    height: 3.75rem;
    display: flex;
    align-items: center;
    width: 210px;
    border-bottom: 1px solid #ededed;
    padding-left: 0px;
    padding-right: 0px;
    .herd-btn {
        margin-left: 1rem;
        width: 4.5rem;
        height: 1.875rem;
        font-size: 12px;
        display: flex;
        background-color: #ffffff;
        // justify-content: space-around;
        width: 100%;
        .button-btn {
            border-radius: 5px;
            cursor: pointer;
            padding: 0px 10px;
            margin-right: 10px;
            border: 1px solid #d9d9d9;
        }
    }
}

.control-wrapper {
    justify-content: space-between;
}

.control-wrapper {
    display: flex;
    height: 3.75rem;
    align-items: center;
    padding: 0 15px;
    border-bottom: 1px solid #ededed;
    line-height: 75px;
    .control-item {
        margin-left: 15px;

        .control-input {
            width: 200px;
            margin-right: 15px;
        }
    }
}

.btn-warp {
    display: flex;
    height: 75px;
    align-items: center;
    padding: 0 15px;
    // border-bottom: 1px solid #ededed;
    line-height: 75px;

    .control-item {
        margin-left: 15px;

        .control-input {
            width: 200px;
            margin-right: 15px;
        }
    }
}

:deep(.el-tree-node__content) {
    height: fit-content;

    .item-wrapper {
        height: 73px;
        display: flex;
        align-content: center;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        .loading-container {
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.5);
            z-index: 999;
        }
        .aside-list-item {
            .item-name {
                font-size: 14px;
                font-weight: bold;
                margin-bottom: 10px;
                text-overflow: ellipsis;
                white-space: nowrap;
                overflow: hidden;
                width: 120px;
            }

            .item-desc {
                font-size: 14px;
                color: #c0c0c0;
                display: flex;
                align-items: center;
                &-sort {
                    margin-left: 12px;
                }
            }
        }
    }
}

:deep(.el-tree-node:focus > .el-tree-node__content) {
    /*设置选中的样式 */
    background-color: #f6f9ff !important;
    color: #000;
}

:deep(.el-tree-node__content:hover) {
    /*设置鼠标飘过的颜色 */
    background: #f6f9ff !important;
    color: #3f78f6;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content:first-child) {
    /*current选中的样式 */
    color: #3f78f6;
    font-weight: bold;
    background-color: #f6f9ff !important;
    position: relative;
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content > .item-wrapper::before) {
    /*current选中的样式 */
    content: '';
    height: 73px;
    width: 3px;
    background: #87b2ff;
    position: absolute;
    left: 0;
    top: 0;
}

.pt0 {
    padding-top: 0;
}

.p0 {
    padding: 0;
}

.table-control {
    display: flex;
    flex-wrap: wrap;

    div {
        margin: 10px;
        // width: 50px;
        cursor: pointer;

        &:hover {
            color: blue;
        }
    }
}

.lijian-tag {
    position: absolute;
    left: 0;
    top: 0;
}

:deep(.el-table th) {
    background-color: transparent !important;
}

.trade-names {
    .trade-editnames {
        height: 15px;
    }
}
.trade-name {
    .edit-name {
        cursor: pointer;
        display: flex;
        align-items: flex-start;
    }
    .label-style {
        display: flex;
        align-items: center;
        margin-top: 2px;
    }
    .litiu {
        background: linear-gradient(#ffb55c, #ff8300);
        color: #fff;
        font-size: 12px;
        width: 43px;
        height: 16px;
        line-height: 16px;
        border-radius: 2px;
        display: flex;
        margin-right: 10px;
    }

    .el-icon {
        display: none;
    }

    &:hover {
        .el-icon {
            display: block;
        }
    }

    .trade-editname {
        height: 15px;
    }
}
.goods-mask {
    position: relative;
    .goods-tag {
        position: absolute;
        bottom: 0;
        background-color: #353646;
        width: 76px;
        text-align: center;
        color: white;
    }
}

.tag-flex-wrap {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin: 5px 0;
    .tag_wrap {
        font-size: 12px;
        padding: 0 10px;
        height: 18px;
        line-height: 18px;
        border-radius: 2px;
        text-align: center;
        margin-right: 10px;
    }
    .color1 {
        color: #e7b0ff;
        background: #faf1ff;
    }
    .color2 {
        color: #ffffff;
        background: #cccccc;
    }
    .color3 {
        color: #ff6f09;
        background: #fff0e5;
    }
}
</style>
